package com.gcpproxy.config;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class RequestIdInterceptor implements HandlerInterceptor {

    private static final Logger logger = LoggerFactory.getLogger(RequestIdInterceptor.class);

    private static final String ATTR_ORIGINAL_THREAD = "__original_thread_name";
     private static final String ATTR_START_NANO = "__start_nano";

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {
        String orig = Thread.currentThread().getName();
        request.setAttribute(ATTR_ORIGINAL_THREAD, orig);
         request.setAttribute(ATTR_START_NANO, System.nanoTime());
        String xRequestId = request.getHeader("x-request-id");
        if (xRequestId != null && !xRequestId.trim().isEmpty()) {
             Thread.currentThread().setName(xRequestId.trim());  
        }
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, @Nullable Exception ex) {
         // 记录 /chat/completions 处理时长
         try {
             Object startObj = request.getAttribute(ATTR_START_NANO);
             if (startObj instanceof Long start && request.getRequestURI() != null) {
                 String uri = request.getRequestURI();
                 if (uri.endsWith("/chat/completions") || uri.contains("/chat/completions")) {
                     long durationMs = (System.nanoTime() - start) / 1_000_000L;
                     String method = request.getMethod();
                     int status = response != null ? response.getStatus() : -1;
                     logger.info("{} {} handled in {} ms (status={})", method, uri, durationMs, status);
                 }
             }
         } catch (Exception ignored) {}

        Object orig = request.getAttribute(ATTR_ORIGINAL_THREAD);
        if (orig instanceof String s) {
             Thread.currentThread().setName(s);
        }
    }
}


